<template>
  <div class="crawler-task-manager">
    <!-- 任务列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>爬虫任务管理</span>
          <el-button type="primary" @click="showCreateDialog" :icon="Plus">
            新建任务
          </el-button>
        </div>
      </template>

      <el-table :data="taskStore.tasks" :loading="taskStore.loading" style="width: 100%">
        <el-table-column prop="taskName" label="任务名称" width="150" />
        <el-table-column prop="keywords" label="关键词" width="200" show-overflow-tooltip />
        <el-table-column prop="cronExpression" label="执行计划" width="120" />
        <el-table-column label="运行统计" width="200">
          <template #default="{ row }">
            <div class="stats-info">
              <div>总运行: {{ row.totalRuns }}</div>
              <div>成功: <span class="success-count">{{ row.successRuns }}</span></div>
              <div>失败: <span class="fail-count">{{ row.failRuns }}</span></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="上次执行" width="180">
          <template #default="{ row }">
            <div v-if="row.lastRunTime">
              <div>{{ formatDateTime(row.lastRunTime) }}</div>
              <el-tag :type="row.lastRunResult === 'SUCCESS' ? 'success' : 'danger'" size="small">
                {{ row.lastRunResult || '未执行' }}
              </el-tag>
            </div>
            <span v-else class="no-data">未执行</span>
          </template>
        </el-table-column>
        <el-table-column prop="executionSummary" label="执行摘要" min-width="320" show-overflow-tooltip/>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="330" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" @click="editTask(row)" :icon="Edit">编辑</el-button>
              <el-button
                  v-if="row.status === 1"
                  size="small"
                  type="warning"
                  @click="pauseTask(row.id)"
                  :icon="VideoPause"
              >
                暂停
              </el-button>
              <el-button
                  v-if="row.status === 2"
                  size="small"
                  type="success"
                  @click="resumeTask(row.id)"
                  :icon="VideoPlay"
              >
                恢复
              </el-button>
              <el-button
                  size="small"
                  type="primary"
                  @click="executeTask(row.id)"
                  :icon="CaretRight"
              >
                立即执行
              </el-button>
              <el-dropdown @command="handleCommand">
                <el-button size="small" :icon="More">
                  更多<el-icon><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{action: 'logs', id: row.id}">
                      <el-icon><Document /></el-icon>查看日志
                    </el-dropdown-item>
                    <el-dropdown-item :command="{action: 'delete', id: row.id}" divided>
                      <el-icon><Delete /></el-icon>删除任务
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建/编辑任务对话框 -->
    <el-dialog
        v-model="showTaskDialog"
        :title="editingTask ? '编辑任务' : '新建任务'"
        width="600px"
    >
      <el-form :model="taskForm" :rules="taskRules" ref="taskFormRef" label-width="120px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="taskForm.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="关键词" prop="keywords">
          <el-input
              v-model="taskForm.keywords"
              type="textarea"
              :rows="2"
              placeholder="请输入关键词，多个关键词用逗号分隔，如：丽江,大理,昆明"
          />
        </el-form-item>
        <el-form-item prop="days" label="爬取天数">
          <el-input-number
              v-model="taskForm.days"
              :min="1"
              :max="15"
              placeholder="爬取天数"
              style="width: 30%"
          />
        </el-form-item>
        <el-form-item label="页码设置">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item prop="startPageIndex">
                <el-input-number
                    v-model="taskForm.startPageIndex"
                    :min="1"
                    :max="9"
                    placeholder="开始页码"
                    style="width: 100%"
                />
                <div class="form-item-tip">开始页码</div>
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-center">
              <span style="line-height: 32px;">至</span>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="endPageIndex">
                <el-input-number
                    v-model="taskForm.endPageIndex"
                    :min="taskForm.startPageIndex || 1"
                    placeholder="结束页码"
                    style="width: 100%"
                />
                <div class="form-item-tip">结束页码（可选）</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="pageSize">
                <el-input-number
                    v-model="taskForm.pageSize"
                    :min="10"
                    :max="30"
                    placeholder="每页数量"
                    style="width: 100%"
                />
                <div class="form-item-tip">每页数量</div>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="form-help-text">
            <el-icon><InfoFilled /></el-icon>
            如果不填写结束页码，则只爬取开始页码的单页数据
          </div>
        </el-form-item>
        <el-form-item label="出发地">
          <el-input
              v-model="taskForm.departureCity"
              type="textarea"
              :rows="2"
              placeholder="请输入路线出发地"
          />
        </el-form-item>
      </el-form>
        <el-form-item label="执行计划" prop="cronExpression">
          <el-select v-model="taskForm.cronExpression" placeholder="选择执行计划" style="width: 100%">
            <el-option label="每小时执行" value="0 0 * * * ?" />
            <el-option label="每天凌晨2点" value="0 0 2 * * ?" />
            <el-option label="每天上午10点" value="0 0 10 * * ?" />
            <el-option label="每天下午6点" value="0 0 18 * * ?" />
            <el-option label="每周一凌晨2点" value="0 0 2 ? * MON" />
            <el-option label="每月1号凌晨2点" value="0 0 2 1 * ?" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="taskForm.cronExpression === 'custom'" label="Cron表达式" prop="customCron">
          <el-input
              v-model="taskForm.customCron"
              placeholder="请输入cron表达式，如：0 0 2 * * ?"
          />
          <div class="cron-help">
            <small>格式：秒 分 时 日 月 周，例如：0 0 2 * * ? 表示每天凌晨2点执行</small>
          </div>
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input
              v-model="taskForm.description"
              type="textarea"
              :rows="2"
              placeholder="请输入任务描述"
          />
        </el-form-item>
      <template #footer>
        <el-button @click="showTaskDialog = false">取消</el-button>
        <el-button type="primary" @click="saveTask" :loading="saving">
          {{ editingTask ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 任务日志对话框 -->
    <el-dialog v-model="showLogDialog" title="任务执行日志" width="1000px">
      <el-table :data="taskStore.currentTaskLogs" max-height="400">
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="耗时" width="80">
          <template #default="{ row }">
            {{ formatDuration(row.duration) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getLogStatusType(row.status)">
              {{ getLogStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="页码范围" width="100">
          <template #default="{ row }">
    <span v-if="row.endPageIndex && row.endPageIndex !== row.startPageIndex">
      {{ row.startPageIndex }}-{{ row.endPageIndex }}页
    </span>
            <span v-else>
      第{{ row.startPageIndex || 1 }}页
    </span>
          </template>
        </el-table-column>
        <el-table-column prop="productCount" label="商品数量" width="80" />
        <el-table-column prop="newProductCount" label="新增" width="60" />
        <el-table-column prop="updateProductCount" label="更新" width="60" />
        <el-table-column prop="executionDetail" label="执行详情" min-width="200" show-overflow-tooltip />
        <el-table-column prop="errorMessage" label="错误信息" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.errorMessage" class="error-message">{{ row.errorMessage }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useCrawlerTaskStore } from '@/stores/crawlerTask'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Edit,
  VideoPause,
  VideoPlay,
  CaretRight,
  More,
  ArrowDown,
  Document,
  Delete, InfoFilled
} from '@element-plus/icons-vue'

const taskStore = useCrawlerTaskStore()

// 对话框状态
const showTaskDialog = ref(false)
const showLogDialog = ref(false)
const editingTask = ref(null)
const saving = ref(false)

// 表单数据
const taskForm = reactive({
  taskName: '',
  keywords: '',
  startPageIndex: 1,
  endPageIndex: 10,
  pageSize: 30,
  days: 1,
  cronExpression: '0 0 2 * * ?',
  customCron: '',
  description: '',
  departureCity: ''
})

// 表单验证规则
const taskRules = {
  taskName: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  keywords: [
    { required: true, message: '请输入关键词', trigger: 'blur' }
  ],
  cronExpression: [
    { required: true, message: '请选择执行计划', trigger: 'change' }
  ],
  customCron: [
    { required: true, message: '请输入cron表达式', trigger: 'blur' }
  ]
}

const taskFormRef = ref()

// 获取状态样式
const getStatusType = (status) => {
  const types = { 0: 'info', 1: 'success', 2: 'warning' }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = { 0: '停用', 1: '启用', 2: '暂停' }
  return texts[status] || '未知'
}

// 获取日志状态样式
const getLogStatusType = (status) => {
  const types = { 0: 'danger', 1: 'success', 2: 'warning' }
  return types[status] || 'info'
}

// 获取日志状态文本
const getLogStatusText = (status) => {
  const texts = { 0: '失败', 1: '成功', 2: '运行中' }
  return texts[status] || '未知'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 格式化持续时间
const formatDuration = (duration) => {
  if (!duration) return ''
  if (duration < 1000) return `${duration}ms`
  if (duration < 60000) return `${(duration / 1000).toFixed(1)}s`
  return `${(duration / 60000).toFixed(1)}min`
}

// 显示创建对话框
const showCreateDialog = () => {
  editingTask.value = null
  resetForm()
  showTaskDialog.value = true
}

// 编辑任务
const editTask = (task) => {
  editingTask.value = task
  Object.assign(taskForm, {
    taskName: task.taskName,
    keywords: task.keywords,
    startPageIndex: task.startPageIndex,
    endPageIndex: task.endPageIndex,
    days: task.days,
    pageSize: task.pageSize,
    cronExpression: task.cronExpression,
    customCron: '',
    description: task.description || '',
    departureCity: task.departureCity || '',
  })
  showTaskDialog.value = true
}

// 保存任务
const saveTask = async () => {
  try {
    await taskFormRef.value.validate()

    saving.value = true

    const taskData = { ...taskForm }
    if (taskData.cronExpression === 'custom') {
      taskData.cronExpression = taskData.customCron
    }
    delete taskData.customCron

    if (editingTask.value) {
      await taskStore.updateTask(editingTask.value.id, taskData)
      ElMessage.success('任务更新成功')
    } else {
      await taskStore.createTask(taskData)
      ElMessage.success('任务创建成功')
    }

    showTaskDialog.value = false
  } catch (error) {
    console.error('保存任务失败:', error)
  } finally {
    saving.value = false
  }
}

// 暂停任务
const pauseTask = async (id) => {
  try {
    await taskStore.pauseTask(id)
    ElMessage.success('任务已暂停')
  } catch (error) {
    ElMessage.error('暂停任务失败')
  }
}

// 恢复任务
const resumeTask = async (id) => {
  try {
    await taskStore.resumeTask(id)
    ElMessage.success('任务已恢复')
  } catch (error) {
    ElMessage.error('恢复任务失败')
  }
}

// 立即执行任务
const executeTask = async (id) => {
  try {
    await ElMessageBox.confirm('确认立即执行该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    await taskStore.executeTask(id)
    ElMessage.success('任务执行已启动')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('执行任务失败')
    }
  }
}

// 查看任务日志
const viewTaskLogs = async (id) => {
  try {
    await taskStore.fetchTaskLogs(id)
    showLogDialog.value = true
  } catch (error) {
    ElMessage.error('获取日志失败')
  }
}

// 删除任务
const deleteTask = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该任务吗？删除后无法恢复。', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await taskStore.deleteTask(id)
    ElMessage.success('任务删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除任务失败')
    }
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command.action) {
    case 'logs':
      viewTaskLogs(command.id)
      break
    case 'delete':
      deleteTask(command.id)
      break
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(taskForm, {
    taskName: '',
    keywords: '',
    startPageIndex: 1,
    endPageIndex: 10,
    pageSize: 30,
    days: 1,
    cronExpression: '0 0 2 * * ?',
    customCron: '',
    description: '',
    departureCity: ''
  })
  taskFormRef.value?.clearValidate()
}

onMounted(() => {
  taskStore.fetchTasks()
})
</script>

<style scoped>
.crawler-task-manager {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .stats-info {
    font-size: 12px;
    line-height: 1.4;

    .success-count {
      color: #67c23a;
      font-weight: bold;
    }

    .fail-count {
      color: #f56c6c;
      font-weight: bold;
    }
  }

  .no-data {
    color: #c0c4cc;
    font-style: italic;
  }

  .cron-help {
    margin-top: 5px;
    color: #909399;
  }

  .error-message {
    color: #f56c6c;
  }

  .text-center {
    text-align: center;
    line-height: 32px;
  }
}
</style>